package com.baibei.ebec;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.home.BuildConfig;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.module.GlideApp;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.SdkConfig;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rae.swift.RaeSharedPreferences;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;
import com.tencent.bugly.beta.Beta;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 设置
 * Created by ChenRui on 2017/8/16 0016 15:00.
 */
@Route(path = AppRouter.ROUTER_SETTING)
public class SettingActivity extends BasicActivity {
    @BindView(R2.id.btn_logout)
    Button mLogout;
    @BindView(R2.id.ll_dev)
    View mDevView;
    @BindView(R2.id.tv_reset_fund_pwd)
    TextView mTvSetFundPwd;
    @BindView(R2.id.tv_responsibility)
    TextView tvResponsibility;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        mDevView.setVisibility(BuildConfig.DEBUG ? View.VISIBLE : View.GONE);
        mLogout.setVisibility(SessionManager.getDefault().isLogin() ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        UserInfo userInfo = SessionManager.getDefault().getUser();
        if (userInfo != null && userInfo.hasSetFundPwd()) {
            mTvSetFundPwd.setText("重置资金密码");
        } else {
            mTvSetFundPwd.setText("设置资金密码");
        }
    }

    @Override
    public IPresenter getBasicPresenter() {
        return null;
    }

    @OnClick(R2.id.tv_help_center)
    public void onHelpCenterClick() {
    }

    @OnClick(R2.id.tv_about_me)
    public void onAboutMeClick() {
        AppRouter.routeToAboutMe(this);
    }

    @OnClick(R2.id.tv_clear_cache)
    public void onClearCacheClick() {
        AppUI.loading(this, "正在清除缓存");

//        ApiFactory.getInstance().clearConfig();

        GlideApp.get(this).clearMemory();
        Observable.just(GlideApp.get(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        AppUI.dismiss();
                        AppUI.success(getContext(), "清除成功");
                    }
                })
                .map(new Function<Glide, Glide>() {
                    @Override
                    public Glide apply(@NonNull Glide glide) throws Exception {
                        glide.clearDiskCache();
                        return glide;
                    }
                })
                .subscribe(new ApiDefaultObserver<Glide>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(Glide glide) {

                    }
                });

    }

    @OnClick(R2.id.tv_feedback)
    public void onFeedbackClick() {
        AppRouter.routeToFeedback(this);
    }

    @OnClick(R2.id.tv_check_update)
    public void onCheckUpdate() {
        Beta.checkUpgrade();
    }

    @OnClick(R2.id.tv_version_update)
    public void onVersionUpdateClick() {
        final String url = "http://192.168.100.169:8088/job/ebec/lastSuccessfulBuild/artifact/app/build/outputs/apk/app-@buildType.apk".replace("@buildType", BuildConfig.BUILD_TYPE);
        StringBuilder sb = new StringBuilder();
        sb.append("构建版本:");
        sb.append(BuildConfig.BUILD_TYPE);
        sb.append("\n代码版本：");
        sb.append(BuildConfig.GIT_COMMIT_SHA);
        sb.append("\n下载地址：");
        sb.append(url);

        new DialogBuilder(this)
                .setMessage(sb.toString())
                .positiveButtonText("立即更新")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog iAppDialog, int i) {
                        iAppDialog.dismiss();
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    }
                })
                .show();
    }

    @OnClick(R2.id.tv_user_info)
    public void onUserInfoClick() {
        if (!SessionManager.getDefault().isLogin()) return;
        StringBuilder sb = new StringBuilder();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        UserInfo userInfo = SessionManager.getDefault().getUser();
        TokenInfo tokenInfo = SessionManager.getDefault().getUserToken();
        sb.append(tokenInfo.toString());
        sb.append("\n");
        sb.append("AppKey=");
        sb.append(ApiConstant.APP_U_KEY_VALUE);
        sb.append("; \nAppSecret=");
        sb.append(new RaeSharedPreferences(this).create(SdkConfig.class).getAppSecret());
        sb.append("; \nDividerId=");
        sb.append(Build.ID);
        sb.append("\n");
        sb.append(gson.toJson(userInfo));

        LogUtils.i("rae", "用户信息：\n" + sb.toString());

        IAppDialog dialog = new DialogBuilder(this)
                .setMessage(sb.toString())
                .show();

        TextView titleView = ((Dialog) dialog).findViewById(R.id.tv_title);
        titleView.setTextIsSelectable(true);
    }

    @OnClick(R2.id.btn_logout)
    public void onLogoutClick() {
        new DialogBuilder(this)
                .setMessage("是否退出登录？")
                .positiveButtonText("退出")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        logout();
                    }
                })
                .show();

    }

    @OnClick(R2.id.tv_reset_fund_pwd)
    public void onResetPwdClickListener() {
        //重置跟设置
        UserInfo userInfo = SessionManager.getDefault().getUser();
        if (userInfo.hasSetFundPwd()) {
            AppRouter.routeToResPayPwd(this);
        } else {
            AppRouter.routeToSetPayPwd(this);
        }
    }

    @OnClick(R2.id.tv_responsibility)
    public void onViewClicked() {
        Intent intent = new Intent(SettingActivity.this, ResponsibilityActivity.class);
        startActivity(intent);
    }
}
